package nancal.mp.mvc.es


import io.swagger.annotations.*
import org.springframework.web.bind.annotation.*
import nancal.mp.db.es.*
import nancal.mp.db.es.entity.*
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.Require
import nbcp.base.comm.*
import nbcp.base.db.IdName
import nbcp.base.extend.*
import nbcp.myoql.db.db
import nbcp.myoql.db.es.RestClientScope
import nbcp.myoql.db.es.component.query
import nbcp.myoql.db.es.component.queryById
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.sql.DataSourceScope
import java.time.LocalDateTime
import javax.servlet.http.*

/**
 * Created by CodeGenerator at 2025-11-09 22:38:33
 */
@Api(description = "file-log", tags = arrayOf("FileLog"))
@RestController
@RequestMapping("/system/file-log")
class FileLogAutoController {

    class RequestVO : FileLog() {
        var userName = ""
    }

    @ApiOperation("列表")
    @PostMapping("/list/{dbId}")
    fun list(
        @PathVariable dbId: String,
        appName: String,
        id: String, //当列表列新一条后，刷新时使用
        userId: String,
        path: String,
        requestId: String,
        msg: String,
        timeFrom: Int?,
        timeTo: Int?,
        startAt: LocalDateTime?,
        endAt: LocalDateTime?,
        @Require skip: Int,
        @Require take: Int,
        request: HttpServletRequest
    ): ListResult<RequestVO> {
        var es = mor.dev.esConnection.query()
            .linkOr({ it.id mongoEquals dbId }, { it.code mongoEquals dbId })
            .toEntity()
            .must().elseThrow { "找不到es数据库连接" }

        var sql = mor.dev.dbConnection.query()
            .where { it.code mongoEquals es.code }
            .toEntity().throwIfNull { "找不到Mongo数据库连接" };

        usingScope(RestClientScope(nbcp.myoql.db.db.es.getRestClient(es.connectionUri))) {

            var list = esr.system.fileLog.query()
                .apply {
                    if (id.HasValue) {
                        this.must { it.id term id }
                    }
                    if (requestId.HasValue) {
                        this.must { it.requestId term requestId }
                    }

                    if (userId.HasValue) {
                        this.must { it.userId term userId }
                    }

                    if (appName.HasValue) {
                        this.must { it.appName term appName }
                    }
                    this.must { it.isRequest term true }

                    if (timeFrom != null && timeFrom > 0) {
                        this.must { it.totalMilliSeconds greaterThanEquals timeFrom }
                    }
                    if (timeTo != null && timeTo > 0) {
                        this.must { it.totalMilliSeconds lessThanEquals timeTo }
                    }

                    if (startAt != null) {
                        this.must { it.recvAt greaterThanEquals startAt }
                    }

                    if (endAt != null) {
                        this.must { it.recvAt lessThanEquals endAt }
                    }

                    if (path.HasValue) {
                        this.must { it.path match_phrase path }
                    }
                    if (msg.HasValue) {
                        this.must { it.msg match_phrase msg }
                    }
                }
                .limit(skip, take)
                .orderByDesc { it.recvAt }
                .toListResult(RequestVO::class.java)

            var listData = list.data;
            listData.forEach {
                //2025-11-13 02:08:24 INFO  ~f3zboz0lqxa8 cf3z1iklbu48w nbcp.myoql.db.sql.component.SqlBaseQueryClip|toMapList:237
                it.msg = it.msg?.split("\n")?.firstOrNull().AsString().split(" ").filter { it.HasValue }.lastOrNull()
                    .AsString()
            }
//            var userIds = listData.map { it.userId }.filter { it.HasValue && it != "-" }.toSet();

//            if (userIds.any()) {
//                usingScope(DataSourceScope(sql.getDataSource())) {
//                    var users = db.sql.rawQuery(
//                        """
//                    select id,name
//                    from app_customer
//                    where id in (:ids)
//                """.trimIndent()
//                    ).paramIn("ids", userIds.toList())
//                        .toList(IdName::class.java)
//
//
//                    users.forEach { user ->
//                        listData.filter { it.userId == user.id }
//                            .forEach {
//                                it.userName = user.name;
//                            }
//                    }
//                }
//            }

//            //如果请求了  hasError ,则补上请求,status
//            if (hasError != null && hasError) {
//                var requestIds = listData.map { it.requestId!! }.distinct();
//
//                esr.system.fileLog.query()
//                    .must { it.requestId termIn requestIds }
//            }

            return list
        }
    }


    @ApiOperation("列表")
    @PostMapping("/list-item/{dbId}")
    fun listItems(
        @PathVariable dbId: String,
        appName: String,
        id: String, //当列表列新一条后，刷新时使用
        userId: String,
        path: String,
        requestId: String,
        logLevel: String,
        msg: String,
        timeFrom: Int?,
        timeTo: Int?,
        startAt: LocalDateTime?,
        endAt: LocalDateTime?,
        @Require skip: Int,
        @Require take: Int,
        request: HttpServletRequest
    ): ListResult<RequestVO> {
        var es = mor.dev.esConnection.query()
            .linkOr({ it.id mongoEquals dbId }, { it.code mongoEquals dbId })
            .toEntity()
            .must().elseThrow { "找不到es数据库连接" }

        var sql = mor.dev.dbConnection.query()
            .where { it.code mongoEquals es.code }
            .toEntity().throwIfNull { "找不到Mongo数据库连接" };

        usingScope(RestClientScope(nbcp.myoql.db.db.es.getRestClient(es.connectionUri))) {

            var list = esr.system.fileLog.query()
                .apply {
                    if (id.HasValue) {
                        this.must { it.id term id }
                    }
                    if (requestId.HasValue) {
                        this.must { it.requestId term requestId }
                    }

                    if (userId.HasValue) {
                        this.must { it.userId term userId }
                    }

                    if (appName.HasValue) {
                        this.must { it.appName term appName }
                    }

                    if (logLevel.HasValue) {
                        this.must { it.logLevel term logLevel }
                    }

                    if (timeFrom != null && timeFrom > 0) {
                        this.must { it.totalMilliSeconds greaterThanEquals timeFrom }
                    }
                    if (timeTo != null && timeTo > 0) {
                        this.must { it.totalMilliSeconds lessThanEquals timeTo }
                    }

                    if (startAt != null) {
                        this.must { it.recvAt greaterThanEquals startAt }
                    }

                    if (endAt != null) {
                        this.must { it.recvAt lessThanEquals endAt }
                    }

                    if (path.HasValue) {
                        this.must { it.path match_phrase path }
                    }
                    if (msg.HasValue) {
                        this.must { it.msg match_phrase msg }
                    }
                }
                .limit(skip, take)
                .orderByDesc { it.recvAt }
                .toListResult(RequestVO::class.java)

            var listData = list.data;
            listData.forEach {
                //2025-11-13 02:08:24 INFO  ~f3zboz0lqxa8 cf3z1iklbu48w nbcp.myoql.db.sql.component.SqlBaseQueryClip|toMapList:237
                it.msg = it.msg?.split("\n")?.firstOrNull().AsString().split(" ").filter { it.HasValue }.lastOrNull()
                    .AsString()
            }
//            var userIds = listData.map { it.userId }.filter { it.HasValue && it != "-" }.toSet();

//            if (userIds.any()) {
//                usingScope(DataSourceScope(sql.getDataSource())) {
//                    var users = db.sql.rawQuery(
//                        """
//                    select id,name
//                    from app_customer
//                    where id in (:ids)
//                """.trimIndent()
//                    ).paramIn("ids", userIds.toList())
//                        .toList(IdName::class.java)
//
//
//                    users.forEach { user ->
//                        listData.filter { it.userId == user.id }
//                            .forEach {
//                                it.userName = user.name;
//                            }
//                    }
//                }
//            }


            return list
        }
    }

    @ApiOperation("详情")
    @PostMapping("/detail/{dbId}/{id}")
    fun detail(
        dbId: String,
        @Require id: String,
        request: HttpServletRequest
    ): ApiResult<FileLog> {
        var conn = mor.dev.esConnection.query()
            .linkOr({ it.id mongoEquals dbId }, { it.code mongoEquals dbId })
            .toEntity()
            .must().elseThrow { "找不到数据库连接" }

        usingScope(RestClientScope(nbcp.myoql.db.db.es.getRestClient(conn.connectionUri))) {
            esr.system.fileLog.queryById(id)
                .toEntity()
                .run {
                    if (this == null) {
                        return ApiResult.error("找不到数据")
                    }

                    return ApiResult.of(this)
                }
        }
    }
}